package ourfilter;

import java.awt.Point;
import java.awt.Rectangle;
import java.awt.image.RenderedImage;

import javax.media.jai.PlanarImage;

import ourImage.OurPlanarImage;
import pimpmypipe.filter.DataTransformationFilter;
import pimpmypipe.interfaces.Writeable;
import pimpmypipe.interfaces.Readable;
import pimpmypipe.pipe.Pipe;

/**
 * This Filter applies the ROI (Region Of Interest) to the given image
 * 
 * All outside will be thrown away
 * 
 * @author Marcel Meraner
 */
public class ROIFilter extends DataTransformationFilter<OurPlanarImage> {
    
    private int _x;
    private int _y;
    private int _width;
    private int _height;
    private boolean _filterEnabled = false;
    

    public void setX(int x) {
        _x = x;
    }

    public void setY(int y) {
        _y = y;
    }

    public void setWidth(int width) {
        _width = width;
    }

    public void setHeight(int height) {
        _height = height;
    }
    
    public ROIFilter(Pipe<OurPlanarImage> in, Pipe<OurPlanarImage> out){
        super(in, out);
        in.setOut(this);
        out.setIn(this);
    }
    public ROIFilter(Readable<OurPlanarImage> in, Writeable<OurPlanarImage> out){
        super(in, out);
    }

    @Override
    protected void process(OurPlanarImage entity) {
        if (_filterEnabled) {
            // Build up ROI rectangle

            Point p = new Point(_x, _y);
            entity.setPoint(p);
            Rectangle rectangle = new Rectangle(_x, _y, _width, _height);
            // Cut the image
            PlanarImage image = PlanarImage.wrapRenderedImage((RenderedImage)entity.getImage().getAsBufferedImage(rectangle, entity.getImage().getColorModel()));
            entity.setImage(image);
        }
    }
   
    /**
     * Set the ROI rectangle
     * X and Y marks the start point (top, left corner)
     * 
     * @param x - x coordinate of the top left corner
     * @param y - y coordinate of the top left corner
     * @param width - rectangle width
     * @param height - rectangle height
     */
    public void setROI(int x, int y, int width, int height){
        _x = x;
        _y = y;
        _width = width;
        _height = height;
    }

    public boolean isEnabled() {
        return _filterEnabled;
    }

    public void setFilterEnabled(boolean enabled) {
        _filterEnabled = enabled;
    }
    
    
}
